<!DOCTYPE html>
<html>
<head><meta charset="utf-8" />
<title>203-文件</title>

<script src="/lib/require/index.js"></script>
<script src="/lib/jquery/index.js"></script>

<!-- 改为引入外部样式 -->
<link rel="stylesheet" href="/css/custom.css">

<!-- Loading mathjax macro -->
<!-- Load mathjax -->
    <script src="/lib/mathjax/index.js"></script>
    <!-- MathJax configuration -->
    <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ['$','$'], ["\\(","\\)"] ],
            displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
            processEscapes: true,
            processEnvironments: true
        },
        // Center justify equations in code and markdown cells. Elsewhere
        // we use CSS to left justify single line equations in code cells.
        displayAlign: 'center',
        "HTML-CSS": {
            styles: {'.MathJax_Display': {"margin": 0}},
            linebreaks: { automatic: true }
        }
    });
    </script>
    <!-- End of mathjax configuration --></head>
<body>
<div class="toc">
<ul>
                        
                        
                        <li class="toc-li-2">
                            <a href="#文件">文件</a>
                        </li>
                    
                
            
                        
                        
                        <li class="toc-li-3">
                            <a href="#打开文件">打开文件</a>
                        </li>
                    
                
            
            
            
            
            
            
            
            
            
            
            
            
            
            
                        
                        
                        <li class="toc-li-3">
                            <a href="#with...as...">with...as...</a>
                        </li>
                    
                
            
                        
                        
                        <li class="toc-li-3">
                            <a href="#常用文件方法">常用文件方法</a>
                        </li>
                    
                
            
            
                        
                        
                        <li class="toc-li-4">
                            <a href="#f.read([size])">f.read([size])</a>
                        </li>
                    
                
            
            
            
            
                        
                        
                        <li class="toc-li-4">
                            <a href="#f.readline([size])">f.readline([size])</a>
                        </li>
                    
                
            
            
            
            
            
                        
                        
                        <li class="toc-li-4">
                            <a href="#f.readlines([hint])">f.readlines([hint])</a>
                        </li>
                    
                
            
            
            
            
            
            
                        
                        
                        <li class="toc-li-4">
                            <a href="#f.write(string)">f.write(string)</a>
                        </li>
                    
                
            
            
            
                        
                        
                        <li class="toc-li-4">
                            <a href="#f.tell()">f.tell()</a>
                        </li>
                    
                
            
            
            
                        
                        
                        <li class="toc-li-4">
                            <a href="#f.seek(offset[,-whence])">f.seek(offset[, whence])</a>
                        </li>
                    
                
            
            
            
            
            
            </ul>
</div>
  <div tabindex="-1" id="notebook" class="border-box-sizing">
    <div class="container" id="notebook-container">

<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[6]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># 打印所有单行变量</span>
<span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="k">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s1">&#39;all&#39;</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="&#25991;&#20214;">&#25991;&#20214;<a class="anchor-link" href="#&#25991;&#20214;">&#182;</a></h2><h3 id="&#25171;&#24320;&#25991;&#20214;">&#25171;&#24320;&#25991;&#20214;<a class="anchor-link" href="#&#25171;&#24320;&#25991;&#20214;">&#182;</a></h3>
<pre><code>open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opene r=None)</code></pre>
<table>
<thead><tr>
<th>模式</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>r</td>
<td>以读方式打开文件，可读取文件信息,默认模式</td>
</tr>
<tr>
<td>w</td>
<td>以写方式打开文件，可向文件写入信息。如文件存在，则清空该文件，再写入新内容</td>
</tr>
<tr>
<td>x</td>
<td>以写模式新建一个文件</td>
</tr>
<tr>
<td>a</td>
<td>以追加模式打开文件（文件指针自动移到文件末尾），如果文件不存在则创建</td>
</tr>
<tr>
<td>+</td>
<td>配合其他模式r,w,a等,以读和写模式</td>
</tr>
<tr>
<td>b</td>
<td>二进制模式</td>
</tr>
</tbody>
</table>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[7]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;test.txt&quot;</span><span class="p">,</span> <span class="s2">&quot;w&quot;</span><span class="p">)</span>  <span class="c1"># 在当前文件夹打开已存在的文件，文件不存在则报错</span>
<span class="p">[</span><span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">dir</span><span class="p">(</span><span class="n">f</span><span class="p">)</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">i</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s1">&#39;_&#39;</span><span class="p">)]</span>  <span class="c1"># --&gt; 文件常用方法</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt output_prompt">Out[7]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>[&#39;buffer&#39;,
 &#39;close&#39;,
 &#39;closed&#39;,
 &#39;detach&#39;,
 &#39;encoding&#39;,
 &#39;errors&#39;,
 &#39;fileno&#39;,
 &#39;flush&#39;,
 &#39;isatty&#39;,
 &#39;line_buffering&#39;,
 &#39;mode&#39;,
 &#39;name&#39;,
 &#39;newlines&#39;,
 &#39;read&#39;,
 &#39;readable&#39;,
 &#39;readline&#39;,
 &#39;readlines&#39;,
 &#39;seek&#39;,
 &#39;seekable&#39;,
 &#39;tell&#39;,
 &#39;truncate&#39;,
 &#39;writable&#39;,
 &#39;write&#39;,
 &#39;writelines&#39;]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<blockquote><p>在对文件进行写入操作之后，一定要牢记一个事情：<code>file.close()</code></p>
</blockquote>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="with...as...">with...as...<a class="anchor-link" href="#with...as...">&#182;</a></h3>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[12]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># 用with语句不用关闭文件</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;test.txt&quot;</span><span class="p">,</span> <span class="s2">&quot;w&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\n</span><span class="s2">This is about &#39;with...as...&#39;&quot;</span><span class="p">)</span>  <span class="c1"># --&gt; 返回字符长度</span>

<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;test.txt&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">f</span><span class="o">.</span><span class="n">readlines</span><span class="p">()</span>  <span class="c1"># --&gt;</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt output_prompt">Out[12]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>29</pre>
</div>

</div>

<div class="output_area">

<div class="prompt output_prompt">Out[12]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>[&#39;\n&#39;, &#34;This is about &#39;with...as...&#39;&#34;]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="&#24120;&#29992;&#25991;&#20214;&#26041;&#27861;">&#24120;&#29992;&#25991;&#20214;&#26041;&#27861;<a class="anchor-link" href="#&#24120;&#29992;&#25991;&#20214;&#26041;&#27861;">&#182;</a></h3><h4 id="f.read([size])">f.read([size])<a class="anchor-link" href="#f.read([size])">&#182;</a></h4><p>如果指定了参数size，就按照该指定长度从文件中读取内容，否则，就读取全文直到EOF</p>
<h4 id="f.readline([size])">f.readline([size])<a class="anchor-link" href="#f.readline([size])">&#182;</a></h4><ul>
<li>如果指定了参数size,则读取指定长度的内容,直到行尾才会读取下一行</li>
<li>如果不指定参数,则一行一行读取</li>
</ul>
<h4 id="f.readlines([hint])">f.readlines([hint])<a class="anchor-link" href="#f.readlines([hint])">&#182;</a></h4><ul>
<li>返回该文件中包含的所有行。</li>
<li>如果设置可选参数hint, 则读取指定长度的字节, 并且将这些字节按行分割</li>
</ul>
<blockquote><p>EOF(End-of-file)</p>
</blockquote>
<h4 id="f.write(string)">f.write(string)<a class="anchor-link" href="#f.write(string)">&#182;</a></h4><p>将 string 写入到文件中, 然后<code>返回</code>写入的字符数</p>
<h4 id="f.tell()">f.tell()<a class="anchor-link" href="#f.tell()">&#182;</a></h4><p>返回文件对象当前所处的位置, 它是从文件开头开始算起的字节数</p>
<h4 id="f.seek(offset[,-whence])">f.seek(offset[, whence])<a class="anchor-link" href="#f.seek(offset[,-whence])">&#182;</a></h4><p>这个函数的功能就是让指针移动。
whence的值：</p>
<ul>
<li>默认值是0，表示从文件开头开始计算指针偏移的量（简称偏移量）。此时offset必须是大于等于0的整数。</li>
<li>是1时，表示从当前位置开始计算偏移量。offset如果是负数，表示从当前位置向前移动，整数表示向后移动。</li>
<li>是2时，表示相对文件末尾移动。</li>
</ul>

</div>
</div>
</div>
    </div>
  </div>
</body>

 


</html>
